<template>
  <div class="home-wrap">
    <el-button type="primary" @click="handleConn">测试连接</el-button>
    <div ref="container" style="height: 800px"></div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import '@xterm/xterm/css/xterm.css'
import { Terminal } from '@xterm/xterm'
import { FitAddon } from '@xterm/addon-fit'

const websockt = ref(null)
const fitAddon = ref({})
const term = ref({})
const container = ref({})
const id = ref(null)

const connData = {
  type: 'conn',
  host: '159.75.77.35',
  port: 22,
  username: 'root',
  password: 'Rom12138@'
}

onMounted(() => {
  id.value = getId()
  connData.id = id.value
})

const handleConn = () => {
  if (websockt.value) {
    return
  }

  term.value = buildTerminal()
  fitAddon.value = new FitAddon()
  term.value.loadAddon(fitAddon.value)
  term.value.open(container.value)
  fitAddon.value.fit()
  connData.cols = term.value.cols
  connData.rows = term.value.rows

  websockt.value = new WebSocket('ws://localhost:10095')
  websockt.value.onmessage = websocketonmessage
  websockt.value.onopen = websocketonopen
  websockt.value.onerror = websocketonerror
  websockt.value.onclose = websocketclose

  term.value.onData((data) => {
    //键盘输入时的回调函数
    const cmdData = {
      id: id.value,
      type: 'cmd',
      cmd: data
    }
    websocketsend(JSON.stringify(cmdData))
  })

  term.value.write('Connecting...\r\n')
}

const buildTerminal = () => {
  const term = new Terminal({
    cursorBlink: true, // 光标闪烁
    cursorStyle: 'block', // 光标样式  null | 'block' | 'underline' | 'bar'
    scrollback: 1000, //回滚
    tabStopWidth: 4 //制表宽度
  })
  return term
}

const websocketonopen = () => {
  websocketsend(JSON.stringify(connData))
}

const websocketonerror = (error) => {
  console.log('websocketonerror:', error)
}

const websocketonmessage = (e) => {
  console.log('websocketonmessage:', e.data)
  const msg = JSON.parse(e.data)
  term.value.write(msg.data)
}

const websocketsend = (data) => {
  websockt.value.send(data)
}

const websocketclose = (e) => {
  console.log('断开连接', e)
}

onBeforeUnmount(() => {
  websockt.value.close()
})

window.onbeforeunload = function () {
  websockt.value.close()
}

const getId = () => {
  const uuid = uuidv4()
  console.log(`uuid:${uuid}`)
  return uuid
}
</script>

<style lang="less" scoped>
.home-wrap {
  padding: 10px;
}
</style>
